import { handleShipCycle, setEvent, setPage, queryString } from '../../utils/index'
import { subNum  } from 'shiptools'
import { TRACER_PAGES, PRODUCT_CODE } from '../../utils/constants'
const pageName = TRACER_PAGES['middle']

Page({

  /**
   * 页面的初始数据
   */
  data: {
    query: {},
    calendarConfig: {},

    notice: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    const _cycle = handleShipCycle(options.cycle)

    const calendarConfig = {
      type: options.type,
      startDate: options.start,
      endDate: options.end,
      cycle: _cycle,
      saleDays: options.saleDays,
      reserveDays: options.reserveDays,
      isRound: options.isRound === '1',
      cityLineId: options.cityLineId,
      fromPage: options.fromPage
    }

    const sellDays = subNum(options.saleDays, options.reserveDays)
    let notice = ''
    if(sellDays > 0 && options.reserveDays > 0) {
      notice = `该航线预售期为${sellDays}天，支持预售期外预约购票，开售后系统将会为您自动下单。`
    }

    this.setData({
      query: options,
      notice,
      calendarConfig
    })
  },

  onShow: function() {
    const query = this.data.query
    setPage(pageName + '?' + queryString(query), PRODUCT_CODE)
  },

  onChoose: function(e) {
    const day = e.detail
    const calendarConfig = this.data.calendarConfig

    const _startDate = calendarConfig.startDate
    const _endDate = calendarConfig.endDate || ''

    const cityLineId = calendarConfig.cityLineId

    const eventChannel = this.getOpenerEventChannel()
    eventChannel.emit('selectDateChannel', { data: day });
    if(!calendarConfig.isRound && calendarConfig.fromPage && ['home', 'sightseeing'].includes(calendarConfig.fromPage)) {
      const { openId='', mobile='', carPlate='', city='' } = this.data.query
      const param = {
        start: day.format,
        end: _endDate,
        cityLineId,
        fromPortId: '',
        toPortId: '',
        openId, mobile, carPlate, city
      }

      const _query = queryString(param)

      const url = `../list?${_query}`
      wx.redirectTo({
        url
      })
      return
    }
    wx.navigateBack({
      delta: 1
    });
  },
  
  onClickNotice: function(e) {
    const notice = this.data.notice
    wx.showModal({
      title: '公告',
      content: notice,
      showCancel: false,
      cancelText: '取消',
      cancelColor: '#333333',
      confirmText: '确定',
      confirmColor: '#00c777',
      success: (result) => {
        if(result.confirm){
          
        }
      },
      fail: ()=>{},
      complete: ()=>{}
    });
  }
})